package com.uduemc.biso.node.module.common.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.uduemc.biso.node.core.common.entities.publishdata.databody.BannerData;
import com.uduemc.biso.node.core.common.entities.publishdata.databody.pagebannerdata.BannerEquip;
import com.uduemc.biso.node.core.common.entities.publishdata.databody.pagebannerdata.BannerItem;
import com.uduemc.biso.node.core.common.entities.surfacedata.bannerdata.Banner;
import com.uduemc.biso.node.core.entities.SBanner;
import com.uduemc.biso.node.core.entities.SBannerItem;
import com.uduemc.biso.node.core.entities.SRepertoryQuote;
import com.uduemc.biso.node.core.entities.custom.BannerItemQuote;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.module.common.mapper.CBannerMapper;
import com.uduemc.biso.node.module.common.service.CBannerService;
import com.uduemc.biso.node.module.service.SBannerItemService;
import com.uduemc.biso.node.module.service.SBannerService;
import com.uduemc.biso.node.module.service.SConfigService;
import com.uduemc.biso.node.module.service.SRepertoryQuoteService;

@Service
public class CBannerServiceImpl implements CBannerService {

	private static final Logger logger = LoggerFactory.getLogger(CBannerServiceImpl.class);

	@Autowired
	private SBannerService sBannerServiceImpl;

	@Autowired
	private SBannerItemService sBannerItemServiceImpl;

	@Autowired
	private SRepertoryQuoteService sRepertoryQuoteServiceImpl;

	@Autowired
	private CBannerMapper cBannerMapper;

	@Autowired
	private SConfigService sConfigServiceImpl;

	@Override
	public Banner getBannerByHostSitePageIdEquip(long hostId, long siteId, long pageId, short equip) {
		SBanner sBanner = sBannerServiceImpl.findByHostSitePageIdEquip(hostId, siteId, pageId, equip);
		if (sBanner == null) {
			return null;
		}
		Banner banner = new Banner();
		banner.setSbanner(sBanner);

		// 图片
		List<BannerItemQuote> listBannerItem = getBannerItemByHostSiteBannerId(hostId, siteId, sBanner.getId(), "0, 4");
		banner.setImageBannerItemQuote(listBannerItem);
		// 视频
		listBannerItem = getBannerItemByHostSiteBannerId(hostId, siteId, sBanner.getId(), "5");
		banner.setVideoBannerItemQuote(listBannerItem);

		return banner;
	}

	@Override
	public List<BannerItemQuote> getBannerItemByHostSiteBannerId(long hostId, long siteId, long bannerId, String repertoryType) {
		List<BannerItemQuote> listBannerItem = cBannerMapper.findBannerItemByHostSiteBannerId(hostId, siteId, bannerId, repertoryType);
		return listBannerItem;
	}

	@Override
	@Transactional
	public Banner insertBanner(Banner banner) {
		SBanner sbanner = banner.getSbanner();
		SBanner insert = sBannerServiceImpl.insert(sbanner);
		if (insert == null) {
			throw new RuntimeException("写入s_banner数据失败！");
		}
		List<BannerItemQuote> listBannerItemQuote = banner.getImageBannerItemQuote();
		if (!CollectionUtils.isEmpty(listBannerItemQuote)) {
			for (BannerItemQuote bannerItemQuote : listBannerItemQuote) {
				SBannerItem sbannerItem = bannerItemQuote.getSbannerItem();
				RepertoryQuote repertoryQuote = bannerItemQuote.getRepertoryQuote();
				SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();

				sbannerItem.setBannerId(insert.getId());
				// 插入 sbannerItem
				SBannerItem insertSBannerItem = sBannerItemServiceImpl.insert(sbannerItem);
				if (insertSBannerItem == null) {
					throw new RuntimeException("写入s_banner_item数据失败！");
				}
				// 插入 sRepertoryQuote
				sRepertoryQuote.setType((short) 9).setAimId(insertSBannerItem.getId());
				SRepertoryQuote insertSRepertoryQuotes = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
				if (insertSRepertoryQuotes == null) {
					throw new RuntimeException("写入s_repertory_quotes数据失败！");
				}
			}
		}
		listBannerItemQuote = banner.getVideoBannerItemQuote();
		if (!CollectionUtils.isEmpty(listBannerItemQuote)) {
			for (BannerItemQuote bannerItemQuote : listBannerItemQuote) {
				SBannerItem sbannerItem = bannerItemQuote.getSbannerItem();
				RepertoryQuote repertoryQuote = bannerItemQuote.getRepertoryQuote();
				SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();

				sbannerItem.setBannerId(insert.getId());
				// 插入 sbannerItem
				SBannerItem insertSBannerItem = sBannerItemServiceImpl.insert(sbannerItem);
				if (insertSBannerItem == null) {
					throw new RuntimeException("写入s_banner_item数据失败！");
				}
				// 插入 sRepertoryQuote
				sRepertoryQuote.setType((short) 9).setAimId(insertSBannerItem.getId());
				SRepertoryQuote insertSRepertoryQuotes = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
				if (insertSRepertoryQuotes == null) {
					throw new RuntimeException("写入s_repertory_quotes数据失败！");
				}
			}
		}

		return getBannerByHostSitePageIdEquip(sbanner.getHostId(), sbanner.getSiteId(), sbanner.getPageId(), sbanner.getEquip());
	}

	@Override
	@Transactional
	public Banner updateBanner(Banner banner) {
		SBanner sbanner = banner.getSbanner();
		Banner findBanner = getBannerByHostSitePageIdEquip(sbanner.getHostId(), sbanner.getSiteId(), sbanner.getPageId(), sbanner.getEquip());
		if (findBanner == null || findBanner.getSbanner() == null) {
			throw new RuntimeException("无法通过 banner 中的 sbanner 的  hostId, siteId, pageId 获取到 banner 数据");
		}
		if (findBanner.getSbanner().getId().longValue() != sbanner.getId().longValue()) {
			throw new RuntimeException("通过 banner 中的 sbanner 的  hostId, siteId, pageId 获取到 findBanner 数据中的 bannerId 与传递过来数据中的 bannerId 不匹配！");
		}
		SBanner sBannerUpdate = sBannerServiceImpl.updateById(sbanner);
		if (sBannerUpdate == null || sBannerUpdate.getId() == null || sbanner.getId().longValue() != sBannerUpdate.getId().longValue()) {
			throw new RuntimeException("修改  s_banner 数据库中的数据异常！");
		}

		// 图片
		List<BannerItemQuote> listBannerItemQuote = banner.getImageBannerItemQuote();
		List<BannerItemQuote> findListBannerItemQuote = findBanner.getImageBannerItemQuote();
		updateBannerItemQuote(sbanner.getId(), listBannerItemQuote, findListBannerItemQuote);

		// 视频
		listBannerItemQuote = banner.getVideoBannerItemQuote();
		findListBannerItemQuote = findBanner.getVideoBannerItemQuote();
		updateBannerItemQuote(sbanner.getId(), listBannerItemQuote, findListBannerItemQuote);

		return getBannerByHostSitePageIdEquip(sbanner.getHostId(), sbanner.getSiteId(), sbanner.getPageId(), sbanner.getEquip());
	}

	@Transactional
	private void updateBannerItemQuote(long bannerId, List<BannerItemQuote> listBannerItemQuote, List<BannerItemQuote> findListBannerItemQuote) {
		if (CollectionUtils.isEmpty(listBannerItemQuote)) {
			// 删除所有的存在的数据
			for (BannerItemQuote bannerItemQuote : findListBannerItemQuote) {
				SBannerItem sbannerItem = bannerItemQuote.getSbannerItem();
				boolean deleteByTypeAimId = sRepertoryQuoteServiceImpl.deleteByTypeAimId((short) 9, sbannerItem.getId());
				if (!deleteByTypeAimId) {
					throw new RuntimeException("删除  sRepertoryQuote 数据异常！");
				}
				sBannerItemServiceImpl.deleteById(sbannerItem.getId());
			}
		} else {
			if (CollectionUtils.isEmpty(findListBannerItemQuote)) {
				// 全部插入数据
				for (BannerItemQuote bannerItemQuote : listBannerItemQuote) {
					SBannerItem sbannerItem = bannerItemQuote.getSbannerItem();
					RepertoryQuote repertoryQuote = bannerItemQuote.getRepertoryQuote();
					SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();

					sbannerItem.setBannerId(bannerId);
					// 插入 sbannerItem
					SBannerItem insertSBannerItem = sBannerItemServiceImpl.insert(sbannerItem);
					if (insertSBannerItem == null) {
						throw new RuntimeException("写入s_banner_item数据失败！");
					}
					// 插入 sRepertoryQuote
					sRepertoryQuote.setType((short) 9).setAimId(insertSBannerItem.getId());
					SRepertoryQuote insertSRepertoryQuotes = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
					if (insertSRepertoryQuotes == null) {
						throw new RuntimeException("写入s_repertory_quotes数据失败！");
					}
				}
			} else {
				logger.info("listBannerItemQuote.size(): " + listBannerItemQuote.size());
				logger.info("findListBannerItemQuote.size(): " + findListBannerItemQuote.size());
				logger.info("listBannerItemQuote: " + listBannerItemQuote.toString());
				logger.info("findListBannerItemQuote: " + findListBannerItemQuote.toString());
				if (listBannerItemQuote.size() == findListBannerItemQuote.size()) {
					// 两个长度相等的情况下，全部进行修改操作
					int len = listBannerItemQuote.size();
					boolean updateBannerItemQuote = updateBannerItemQuote(listBannerItemQuote, findListBannerItemQuote, len);
					if (!updateBannerItemQuote) {
						throw new RuntimeException("更新s_banner_item、s_repertory_quote数据失败！");
					}
				} else if (listBannerItemQuote.size() > findListBannerItemQuote.size()) {
					int len = findListBannerItemQuote.size();
					boolean updateBannerItemQuote = updateBannerItemQuote(listBannerItemQuote, findListBannerItemQuote, len);
					if (!updateBannerItemQuote) {
						throw new RuntimeException("更新s_banner_item、s_repertory_quote数据失败！");
					}
					// 修改完成后进行插入新增的数据
					for (int i = len; i < listBannerItemQuote.size(); i++) {
						BannerItemQuote bannerItemQuote = listBannerItemQuote.get(i);
						SBannerItem sbannerItem = bannerItemQuote.getSbannerItem();
						RepertoryQuote repertoryQuote = bannerItemQuote.getRepertoryQuote();
						SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();

						sbannerItem.setBannerId(bannerId);
						// 插入 sbannerItem
						SBannerItem insertSBannerItem = sBannerItemServiceImpl.insert(sbannerItem);
						if (insertSBannerItem == null) {
							throw new RuntimeException("写入s_banner_item数据失败！");
						}
						// 插入 sRepertoryQuote
						sRepertoryQuote.setType((short) 9).setAimId(insertSBannerItem.getId());
						SRepertoryQuote insertSRepertoryQuotes = sRepertoryQuoteServiceImpl.insert(sRepertoryQuote);
						if (insertSRepertoryQuotes == null) {
							throw new RuntimeException("写入s_repertory_quotes数据失败！");
						}
					}
				} else if (listBannerItemQuote.size() < findListBannerItemQuote.size()) {
					int len = listBannerItemQuote.size();
					boolean updateBannerItemQuote = updateBannerItemQuote(listBannerItemQuote, findListBannerItemQuote, len);
					if (!updateBannerItemQuote) {
						throw new RuntimeException("更新s_banner_item、s_repertory_quote数据失败！");
					}
					// 修改完成后进行删除多余的数据
					for (int i = len; i < findListBannerItemQuote.size(); i++) {
						BannerItemQuote bannerItemQuote = findListBannerItemQuote.get(i);
						SBannerItem sbannerItem = bannerItemQuote.getSbannerItem();
						boolean deleteByTypeAimId = sRepertoryQuoteServiceImpl.deleteByTypeAimId((short) 9, sbannerItem.getId());
						if (!deleteByTypeAimId) {
							throw new RuntimeException("删除  sRepertoryQuote 数据异常！");
						}
						sBannerItemServiceImpl.deleteById(sbannerItem.getId());
					}
				}
			}
		}
	}

	@Transactional
	private boolean updateBannerItemQuote(List<BannerItemQuote> listBannerItemQuote, List<BannerItemQuote> findListBannerItemQuote, int len) {
		for (int i = 0; i < len; i++) {
			BannerItemQuote bannerItemQuote = listBannerItemQuote.get(i);
			BannerItemQuote findBannerItemQuote = findListBannerItemQuote.get(i);

			SBannerItem sbannerItem = bannerItemQuote.getSbannerItem();
			SRepertoryQuote sRepertoryQuote = bannerItemQuote.getRepertoryQuote().getSRepertoryQuote();

			SBannerItem findSbannerItem = findBannerItemQuote.getSbannerItem();
			SRepertoryQuote findSRepertoryQuote = findBannerItemQuote.getRepertoryQuote().getSRepertoryQuote();

			findSbannerItem.setConfig(sbannerItem.getConfig());

			SBannerItem updateSBannerItem = sBannerItemServiceImpl.updateById(findSbannerItem);
			if (updateSBannerItem == null || updateSBannerItem.getId() == null
					|| updateSBannerItem.getId().longValue() != findSbannerItem.getId().longValue()) {
				throw new RuntimeException("更新s_banner_item数据失败！");
			}

			findSRepertoryQuote.setRepertoryId(sRepertoryQuote.getRepertoryId()).setConfig(sRepertoryQuote.getConfig());
			SRepertoryQuote updateSRepertoryQuote = sRepertoryQuoteServiceImpl.updateById(findSRepertoryQuote);
			if (updateSRepertoryQuote == null || updateSRepertoryQuote.getId() == null
					|| updateSRepertoryQuote.getId().longValue() != findSRepertoryQuote.getId().longValue()) {
				throw new RuntimeException("更新s_repertory_quote数据失败！");
			}
		}
		return true;
	}

	@Transactional
	@Override
	public void publish(long hostId, long siteId, long pageId, BannerData bannerData) {
		if (bannerData == null) {
			return;
		}
		short siteBanner = bannerData.getSiteBanner();
		// 修改 s_config 中的 site_banner 配置
		sConfigServiceImpl.updateSiteBanner(hostId, siteId, siteBanner);

		long pageDataId = pageId;
		if (siteBanner == (short) 1) {
			pageDataId = 0;
		}
		SBanner sBanner;
		SBanner save;
		BannerEquip pc = bannerData.getPc();
		if (pc != null) {
			// 获取 pc banner 的数据
			sBanner = sBannerServiceImpl.findByHostSitePageIdEquip(hostId, siteId, pageDataId, (short) 1);
			if (sBanner == null) {
				sBanner = new SBanner();
				sBanner.setHostId(hostId).setSiteId(siteId).setPageId(pageDataId).setEquip((short) 1).setType(pc.getType()).setIsShow(pc.getIsShow())
						.setConfig(pc.getConfig());
			} else {
				sBanner.setType(pc.getType()).setIsShow(pc.getIsShow()).setConfig(pc.getConfig());
			}

			save = sBannerServiceImpl.save(sBanner);
			if (save == null || save.getId() == null || save.getId().longValue() < 1) {
				throw new RuntimeException("保存 s_banner 数据出现异常 sBanner： " + sBanner.toString());
			}

			List<BannerItem> bannerPcItem = pc.getImageItem();
			List<BannerItemQuote> listBannerItemQuote = getBannerItemByHostSiteBannerId(hostId, siteId, save.getId(), "0, 4");
			sBannerItemServiceImpl.save(hostId, siteId, save.getId(), bannerPcItem, listBannerItemQuote);
			bannerPcItem = pc.getVideoItem();
			listBannerItemQuote = getBannerItemByHostSiteBannerId(hostId, siteId, save.getId(), "5");
			sBannerItemServiceImpl.save(hostId, siteId, save.getId(), bannerPcItem, listBannerItemQuote);
		}

		BannerEquip wap = bannerData.getWap();
		if (wap != null) {
			// 获取 wap banner 的数据
			sBanner = sBannerServiceImpl.findByHostSitePageIdEquip(hostId, siteId, pageDataId, (short) 2);
			if (sBanner == null) {
				sBanner = new SBanner();
				sBanner.setHostId(hostId).setSiteId(siteId).setPageId(pageDataId).setEquip((short) 1).setType(wap.getType()).setIsShow(wap.getIsShow())
						.setConfig(wap.getConfig());
			} else {
				sBanner.setType(wap.getType()).setIsShow(wap.getIsShow()).setConfig(wap.getConfig());
			}

			save = sBannerServiceImpl.save(sBanner);
			if (save == null || save.getId() == null || save.getId().longValue() < 1) {
				throw new RuntimeException("保存 s_banner 数据出现异常 sBanner： " + sBanner.toString());
			}

			List<BannerItem> bannerWapItem = wap.getImageItem();
			List<BannerItemQuote> listBannerItemQuote = getBannerItemByHostSiteBannerId(hostId, siteId, save.getId(), "0, 4");
			sBannerItemServiceImpl.save(hostId, siteId, save.getId(), bannerWapItem, listBannerItemQuote);
			bannerWapItem = wap.getVideoItem();
			listBannerItemQuote = getBannerItemByHostSiteBannerId(hostId, siteId, save.getId(), "5");
			sBannerItemServiceImpl.save(hostId, siteId, save.getId(), bannerWapItem, listBannerItemQuote);
		}

	}

	@Transactional
	@Override
	public void delete(long hostId, long siteId, long pageId) {
		List<SBanner> listSBanner = sBannerServiceImpl.findByHostSitePageId(hostId, siteId, pageId);
		if (CollectionUtils.isEmpty(listSBanner)) {
			return;
		}
		List<Long> bannerItemIds = new ArrayList<Long>();

		Iterator<SBanner> iterator = listSBanner.iterator();
		while (iterator.hasNext()) {
			SBanner sBanner = iterator.next();
			List<SBannerItem> listSBannerItem = sBannerItemServiceImpl.findByHostSiteBannerId(hostId, siteId, sBanner.getId());
			if (CollectionUtils.isEmpty(listSBannerItem)) {
				continue;
			}
			Iterator<SBannerItem> iteratorSBannerItem = listSBannerItem.iterator();
			while (iteratorSBannerItem.hasNext()) {
				SBannerItem sBannerItem = iteratorSBannerItem.next();
				bannerItemIds.add(sBannerItem.getId());
			}

			// 删除bannerItem数据
			int deleteByHostSiteBannerId = sBannerItemServiceImpl.deleteByHostSiteBannerId(hostId, siteId, sBanner.getId());
			if (deleteByHostSiteBannerId < 1) {
				throw new RuntimeException("删除 sBannerItem 数据失败: bannerId" + sBanner.getId());
			}
		}

		if (!CollectionUtils.isEmpty(bannerItemIds)) {
			// 删除资源引用
			boolean deleteByTypeAimId = sRepertoryQuoteServiceImpl.deleteByHostSiteAimIdAndType(hostId, siteId, (short) 9, bannerItemIds);
			if (!deleteByTypeAimId) {
				throw new RuntimeException("通过 type 和 aimIds 删除 资源引用数据失败！bannerItemIds: " + bannerItemIds);
			}
		}

		// 最后删除banner数据
		int deleteByHostSitePageId = sBannerServiceImpl.deleteByHostSitePageId(hostId, siteId, pageId);
		if (deleteByHostSitePageId < 1) {
			throw new RuntimeException("删除 sBanner 数据失败: pageId" + pageId);
		}
	}

}
